#include "xmppcore/jabberid.h"

namespace yoohoo_xmppcore {

JabberId::JabberId(QString domain) : _domain(domain) {
}

JabberId::JabberId(QString node, QString domain) : _node(node), _domain(domain) {
}

JabberId::JabberId(QString node, QString domain, QString resource) :
		_node(node), _domain(domain), _resource(resource) {
}

JabberId::JabberId(const JabberId& other) : _node(other._node),
		_domain(other._domain), _resource(other._resource) {
}

void JabberId::setNode(QString node) {
	_node = node;
}

QString JabberId::node() const {
	return _node;
}

void JabberId::setDomain(QString domain) {
	_domain = domain;
}

QString JabberId::domain() const {
	return _domain;
}

void JabberId::setResource(QString resource) {
	_resource = resource;
}

QString JabberId::resource() const {
	return _resource;
}

QString JabberId::toString() const {
	Q_ASSERT(_domain.size() > 0);

	QString string;
	if (_node.size() > 0)
		string.append(_node).append("@");

	string.append(_domain);

	if (_resource.size() > 0) {
		string.append("/").append(_resource);
	}

	return string;
}

QString JabberId::bareId() const {
	if ("" == _node)
		return _domain;

	return _node + "@" + _domain;
}

bool JabberId::fromString(const QString& jidString) {
	if (jidString.length() == 0)
		return false;

	QChar at('@');
	int atIndex = jidString.indexOf(at);
	if (atIndex == -1) {
		_domain = jidString;
	} else {
		_node = jidString.left(atIndex);
		QString domainAndResource = jidString.mid(atIndex + 1);

		// two '@' chars
		if (domainAndResource.indexOf(at) != -1)
			return false;

		QChar slash = QChar('/');
		int slashIndex = domainAndResource.indexOf(slash);
		if (slashIndex == -1) {
			_domain = domainAndResource;
		} else {
			_domain = domainAndResource.left(slashIndex);
			_resource = domainAndResource.mid(slashIndex + 1);

			// two '/' chars
			if (_resource.indexOf(slash) != -1)
				return false;
		}
	}

	if (_domain.length() == 0 || _domain.length() > 1023)
		return false;

	if (_node.length() > 1023 || _resource.length() > 1023)
		return false;

	return true;
}

bool JabberId::operator==(const JabberId& other) {
	return (_node == other.node() && _domain == other.domain() && _resource == other.resource());
}

bool JabberId::operator!=(const JabberId& other) {
	return !(*this == other);
}

}
